package org.whuims.web.util.pdf2xml;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhongwei on 2017/6/15.
 */
@Component
public class Pdf2Xml {

    @Autowired
    private HttpServletRequest request;

    public String pdf2Xml(String pdfLocation) {
        File inputFile = new File(request.getServletContext().getRealPath("/") + "resource/docs/" + pdfLocation);
        TextExtractor te;
        try {
            te = parsePdf(inputFile);
            return te.toXml();
        } catch (IOException e) {
            System.err.println("Couldn't read file '" + inputFile + "'.");
        }
        return null;
    }

    private TextExtractor parsePdf(File f) throws IOException {
        PDDocument doc = PDDocument.load(f);

        PDDocumentCatalog docCat = doc.getDocumentCatalog();

        PDPageNode root = docCat.getPages();
        List pages = new ArrayList();
        root.getAllKids(pages);

        TextExtractor te = new TextExtractor();

        for (Object p : pages) {
            PDPage page = (PDPage) p;

            te.setShouldSeparateByBeads(false);
            try {
                te.processStream(page,
                        page.getResources(),
                        page.getContents().getStream());
            } catch (Exception e) {

            }
        }

        doc.close();

        return te;
    }
}
